import { baseURL, version } from './config'
import { getUserInfo, clearUserInfo } from './user'

let loadingCount = 0
const Request = ({ url, data, method }) => {
  loadingCount++
  wx.showLoading({
    title: '',
    icon: 'loading'
  })
  const header = {
    Authorization: getUserInfo()?.token ? 'Bearer ' + getUserInfo()?.token : '',
    platform: 'WXMP',
    version
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseURL + url,
      data,
      header,
      method,
      timeout: 15000,
      success: ({ data: httpData, statusCode, errMsg }) => {
        // http请求失败
        if (Number(statusCode) !== 200) {
          wx.showToast({
            title: `${statusCode}-${errMsg}`,
            icon: 'none'
          })
          resolve([`${statusCode}-${errMsg}`, null])
          return
        }

        const { code, data, msg } = httpData
        // 失败统一处理
        if (![0, 200].includes(Number(code))) {
          if (Number(code) === 401) {
            clearUserInfo()
            wx.switchTab({
              url: '/pages/usercenter/usercenter',
              success: (res) => {
                wx.showToast({
                  title: '请先登录',
                  icon: 'none'
                })
              }
            })
            return
          }

          wx.showToast({
            title: `${code}-${msg}`,
            icon: 'none'
          })
          resolve([`${code}-${msg}`, null])
          return
        }
        // 成功返回
        resolve([undefined, data])
      },
      fail: ({ errMsg }) => {
        console.log(errMsg)
        wx.showToast({
          title: `${errMsg}`,
          icon: 'none'
        })
        resolve([errMsg, null])
      },
      complete: (res) => {
        if (loadingCount === 1) {
          wx.hideLoading()
        }
        loadingCount--
      }
    })
  })
}

export const Get = ({ url, data }) => Request({ url, data, method: 'GET' })

export const Post = ({ url, data }) => Request({ url, data, method: 'POST' })

export const Put = ({ url, data }) => Request({ url, data, method: 'PUT' })

export const Delete = ({ url, data }) => Request({ url, data, method: 'DELETE' })
